Golang encoding/xml.Encoder.Indent() function example
package encoding/xml
Indent sets the encoder to generate XML in which each element begins on a new indented line that starts with prefix and is followed by one or more copies of indent according to the nesting depth.
Golang encoding/xml.Encoder.Indent() function usage example
package main
import (
"encoding/xml"
"fmt"
"os"
"reflect"
)
type Address struct {
City, State string
City, State string
}
type Person struct {
XMLName xml.Name `xml:"person"`
Id int `xml:"id,attr"`
FirstName string `xml:"name>first"`
LastName string `xml:"name>last"`
Age int `xml:"age"`
Height float32 `xml:"height,omitempty"`
Married bool
Address
Comment string `xml:",comment"`
}
func main() {
v := &Person{Id: 13, FirstName: "John", LastName: "Doe", Age: 42}
v.Comment = " Need more details. "
v.Address = Address{"Hanga Roa", "Easter Island"}
encoder := xml.NewEncoder(os.Stdout)
encoder.Indent(" ", " ") // <---- here
newtoken := xml.StartElement{
Name : xml.Name{
Space: "",
Local: "location",
},
}
if err := encoder.EncodeToken(newtoken); err != nil {
fmt.Println(err)
}
start := xml.StartElement{
Name: xml.Name{
Space: "",
Local: reflect.Indirect(reflect.ValueOf(v)).Type().Name(),
},
Attr: []xml.Attr{{xml.Name{"", "xmlns"}, "https://socketloop.com/xmldoc/2014-09-01/"}},
}
if err := encoder.EncodeElement(v, start); err != nil {
fmt.Println(err)
}
encoder.Flush()
}
Reference :
Advertisement
Something interesting
Tutorials
+21.9k Golang : Use TLS version 1.2 and enforce server security configuration over client
+18.4k Golang : How to remove certain lines from a file
+12.3k Golang : Display list of countries and ISO codes
+7.2k Golang : Null and nil value
+8.3k Swift : Convert (cast) Character to Integer?
+13.5k Facebook PHP getUser() returns 0
+33.6k Golang : How to check if slice or array is empty?
+12.3k Golang : How to check if a string starts or ends with certain characters or words?
+4.9k HTTP common errors and their meaning explained
+5.4k Golang : Get S3 or CloudFront object or file information
+10.7k Golang : Get currencies exchange rates example
+7.9k Golang : Ways to recover memory during run time.